import {time, offset} from './config'

export default {
  bind(el, binding) {
    const stop = binding.modifiers.stop || false
    const prevent = binding.modifiers.prevent || false
    const tapStatus = binding.modifiers.status || false
    const callback = binding.value
    let timer = null
    let Event = {
      el
    }
    let moveCount = 0
    let status = false
    el.addEventListener('touchstart', function(event){

      if(event.changedTouches.length > 1){
        status = false
        return
      }

      moveCount = 0
      status = true

      timer = setTimeout(() => {
        timer = null
        status = false

        if(!status || !tapStatus)
          return

        Event.type = 'taperror'
        Event.e = event

        callback(Object.assign({}, Event))
      }, time)

      if(stop)
        event.stopPropagation()
      if(prevent)
        event.preventDefault()

      if(!tapStatus)
        return

      Event.type = 'tapstart'
      Event.e = event

      callback(Object.assign({}, Event))

    }, false)

    el.addEventListener('touchmove', function(event){
      if(event.changedTouches.length > 1){
        status = false
        return
      }

      if(!status)
        return

      moveCount += 1
      if(moveCount > offset){
        clearTimeout(timer)
        timer = null

        if(!status)
          return

        status = false

        if(!tapStatus)
          return

        Event.type = 'taperror'
        Event.e = event
        callback(Object.assign({}, Event))
      }

      if(stop)
        event.stopPropagation()
      if(prevent)
        event.preventDefault()

    }, false)

    el.addEventListener('touchend', function(event) {

      if(!status)
        return

      clearTimeout(timer)
      timer = null

      Event.e = event
      Event.type = 'tap'

      callback(Object.assign({}, Event))

      if(stop)
        event.stopPropagation()
      if(prevent)
        event.preventDefault()

    }, false)

    el.addEventListener('touchleave', function(event){

      clearTimeout(timer)
      timer = null

      if(prevent)
        event.preventDefault()

      if(!status || !tapStatus)
        return

      Event.e = event
      Event.type = 'taperror'
      status = false

      callback(Object.assign({}, Event))

    }, false)

    el.addEventListener('touchcancel', function(event){

      clearTimeout(timer)
      timer = null

      if(stop)
        event.stopPropagation()
      if(prevent)
        event.preventDefault()

      if(!status || !tapStatus)
        return

      Event.e = event
      Event.type = 'taperror'
      status = false

      callback(Object.assign({}, Event))

    }, false)
  }
}
